﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.Infrastructure.Authentication;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.WebApp.Models.Ado;
using XSTDZ.ERP.Core.Extentions;
namespace XSTDZ.ERP.WebApp.Controllers
{
    /// <summary>
    /// 工资工单 管理
    /// </summary>
    public class WagesController : Controller
    {
        //
        // GET: /Piece/
        private readonly IWorkGroupService workGroupServiceImpl = ServiceLocator.Instance.GetService<IWorkGroupService>();
        public ActionResult Index()
        {
            return View();
        }
        #region 查看详细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id)
        {
            var billModel = workGroupServiceImpl.GetWagesBill(id);
            GetWorkGroupNames("");
            return View(billModel);
        }
        #endregion

        #region 保存和提交统一入口
        [NoAuthorizated("AddAndConfirm")]
        [HttpPost]
        public ActionResult AddAndConfirm(WagesBillDto roductInBillDto)
        {
            bool isConfirm = Convert.ToBoolean(Request["isConfirm"]);
            //订单已确认
            if (roductInBillDto.BillState > 0)
            {
                return new EmptyResult();
            }
            //保存(或更新)
            var resultRst = Add(roductInBillDto, isConfirm) as ContentResult;
            return Content(resultRst.Content.ToString());
        }
        #endregion
        #region 计件表
         [NoAuthorizated("Add")]
        public ActionResult Add(Guid? id)
        {
            WagesBillDto wg = new WagesBillDto();
            wg.StartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            wg.EndDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,23,59,59);
            if (id.HasValue)
            {
                Guid wid = Guid.Empty;
                Guid.TryParse(id.Value.ToString(), out wid);
                wg = workGroupServiceImpl.GetWagesBill(wid);

            }
            else
            {
                wg.WagesBillNO = new BusinessBillNoCreator().CreateWageNextNO();
            }
            GetWorkGroupNames("");
            return View(wg);
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(WagesBillDto workGroup,bool isConfirm)
        {
            #region 处理介面元素
            var model = new ProductCheckBillModel();
            var result = Request.Form["hidProductBillItems"];

            result = result.Replace("null", "0");

            var detailItems = model.ConvertJosnToClass<WagesBillDetailDto>(result);
            if (!string.IsNullOrEmpty(result) && detailItems == null)
            {
                return Content("0");//明细行异常
            }
            //
            var uid = UserModel.GetLoginUserId(this.HttpContext);
            if (workGroup.Id != null && workGroup.Id.Equals(Guid.Empty))
            {
                workGroup.UpdateID = uid;
            }
            else
            {
                workGroup.CreateID = uid;
            }
            //
            var userCounts=detailItems.Count;
            detailItems.Each(t => {
                //t.WagesBillNO = workGroup.WagesBillNO;
                //t.StartDate = workGroup.StartDate;
                //t.EndDate = workGroup.EndDate;
                //t.WorkGroupID = workGroup.WorkGroupID;
               // t.WagesBillID = workGroup.Id ?? Guid.Empty;
                #region 费用计算
                /*
                if (t.IsHeadman == 1)
                {
                    t.Wages = t.PieceWages - t.ScrapMoney + t.SubsidyMoney  
                        - t.LiftMoney - t.OtherMoney
                        + (-t.HeadmanAward)
                        ;

                }
                else
                {
                    t.Wages = t.PieceWages - t.ScrapMoney+ t.SubsidyMoney 
                         - t.LiftMoney - t.OtherMoney
                         -(-t.HeadmanAward);
                }
                */
                t.Wages = t.PieceWages + t.ScrapMoney + t.SubsidyMoney
                         + t.LiftMoney + t.OtherMoney
                         + t.HeadmanAward;
                #endregion
            });
            #endregion
            if (isConfirm)
            {
                workGroup.BillState = 1;
                workGroup.IsSettle = 1;
            }

            if (ModelState.IsValid)
            {
                this.workGroupServiceImpl.AddWagesBills(workGroup,detailItems);
                return Content("9");
              //  ViewBag.PostState = 9;
            }
            return Content("0");
          //  return View(workGroup);
        }
         [NoAuthorizated("Delete")]
        public ActionResult Delete(Guid id)
        {
            workGroupServiceImpl.DeleteWorkGroup(id);
            return Content("9");
        }
        #endregion
       
        #region 获得计件表列表
        [NoAuthorizated("GetJsonOfWages")]
        public ActionResult GetJsonOfWages()
        {
            /*
            int recordCount = 0;
            var workGroupService = workGroupServiceImpl.GetWagesBill(out recordCount, 1, 100);
            if (workGroupService != null && workGroupService.Count() != 0)
            {
                var jsonResult = workGroupService.Select(u => { u.BillStateName = u.IsSettle == 0 ? "" : "已结算"; return u; });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + recordCount + "\"}";
                return Content(target);
            }
            return View();
            */
            return Content(new BLLQuery().GetWagesBills(this.HttpContext));
        }
        //获得一次计算的一个工作组数据
        [NoAuthorizated("GetJsonOfWagesBills")]
        public ActionResult GetJsonOfWagesBills(bool isInit)
        {
            if (isInit)
            {
                return Content(new BLLQuery().GetWagesBillDetails(this.HttpContext));
            }
            else
            {
                return Content(new BLLQuery().GetWagesBillDetailsById(this.HttpContext));
            }
        }
        #endregion

        #region 码表获得工作组名称
        private void GetWorkGroupNames(string _groupId)
        {
            var model = new RefeModel();
            var refeList = model.GetRefeByModuleName(RefeTypeOption.工作组名称);
            ViewBag.WorkGroupNames = model.GetDropDownListItemsById(refeList, _groupId);
        }
        #endregion
    }
}
